<template>
  <div
    class="guess-panel bg-white shadow-lg rounded-lg overflow-hidden"
    :class="[
      panelClass,
      {
        'fixed bottom-0 left-0 right-0 md:relative md:bottom-auto': isMobile,
        'h-[50vh] md:h-auto': isMobile && !isCollapsed,
        'h-12': isMobile && isCollapsed,
      },
    ]"
  >
    <!-- 移动端折叠控制栏 -->
    <div
      v-if="isMobile"
      class="flex items-center justify-between px-4 py-2 bg-gray-50 cursor-pointer"
      @click="$emit('toggle-collapse')"
    >
      <span class="text-sm font-medium text-gray-700">
        {{ isCollapsed ? "展开猜词面板" : "收起猜词面板" }}
      </span>
      <svg
        class="w-5 h-5 text-gray-500 transform transition-transform"
        :class="{ 'rotate-180': !isCollapsed }"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M19 9l-7 7-7-7"
        />
      </svg>
    </div>

    <div v-show="!isMobile || !isCollapsed" class="guess-content p-4">
      <!-- 当前词汇显示（仅绘画者可见） -->
      <div v-if="isDrawer && currentWord" class="current-word mb-4">
        <div
          class="bg-blue-100 border border-blue-300 rounded-lg p-3 text-center"
        >
          <span class="text-sm text-blue-600">你要画的词是：</span>
          <span class="text-lg font-bold text-blue-800 ml-2">{{
            currentWord
          }}</span>
        </div>
      </div>

      <!-- 等待开始游戏 -->
      <div v-if="gameStatus === 'waiting'" class="waiting-area mb-4">
        <div
          class="text-center p-4 bg-yellow-50 border border-yellow-200 rounded-lg"
        >
          <p class="text-yellow-800 mb-2">等待游戏开始...</p>
          <p class="text-sm text-yellow-600 mb-3">需要至少2个玩家才能开始</p>
          <button
            v-if="canStartGame"
            @click="$emit('start-game')"
            class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
          >
            开始游戏
          </button>
        </div>
      </div>

      <!-- 猜词区域 -->
      <div
        v-if="!isDrawer && gameStatus === 'drawing'"
        class="guess-input mb-4"
      >
        <div class="flex gap-2">
          <input
            v-model="guessInput"
            @keyup.enter="submitGuess"
            type="text"
            placeholder="输入你的猜测..."
            class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            :disabled="gameStatus !== 'drawing'"
          />
          <button
            @click="submitGuess"
            :disabled="!guessInput.trim() || gameStatus !== 'drawing'"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
          >
            猜
          </button>
        </div>
      </div>

      <!-- 游戏信息 -->
      <div class="game-info mb-4">
        <div
          class="flex justify-between items-center text-sm text-gray-600 mb-2"
        >
          <span>时间剩余: {{ timeLeft }}s</span>
          <span>状态: {{ gameStatusText }}</span>
        </div>

        <!-- 游戏进度 -->
        <div v-if="gameStatus !== 'waiting'" class="mb-2">
          <div class="flex justify-between text-xs text-gray-500 mb-1">
            <span>第 {{ currentRound }} / {{ maxRounds }} 轮</span>
            <span>{{ Math.round(gameProgress) }}%</span>
          </div>
          <div class="w-full bg-gray-200 rounded-full h-1">
            <div
              class="bg-green-500 h-1 rounded-full transition-all duration-300"
              :style="{ width: `${gameProgress}%` }"
            />
          </div>
        </div>

        <!-- 时间进度条 -->
        <div class="w-full bg-gray-200 rounded-full h-2">
          <div
            class="h-2 rounded-full transition-all duration-1000"
            :class="
              timeLeft > 20
                ? 'bg-blue-500'
                : timeLeft > 10
                ? 'bg-yellow-500'
                : 'bg-red-500'
            "
            :style="{ width: `${timeProgress}%` }"
          />
        </div>
      </div>

      <!-- 聊天记录 -->
      <!-- 聊天消息区域 -->
      <div ref="chatContainer" class="chat-messages mb-4 flex-1">
        <div
          class="h-full min-h-[120px] overflow-y-auto border border-gray-200 rounded-lg p-3"
        >
          <div
            v-if="messages.length === 0"
            class="text-center text-gray-500 text-sm py-2"
          >
            还没有消息
          </div>
          <div
            v-else
            v-for="(message, index) in messages"
            :key="index"
            class="mb-1"
          >
            <span
              class="text-xs md:text-sm"
              :class="getMessageClass(message.type)"
            >
              {{ message.playerName }}: {{ message.content }}
            </span>
          </div>
        </div>
      </div>

      <!-- 玩家列表 -->
      <div class="players-list">
        <h3 class="text-xs md:text-sm font-medium text-gray-700 mb-2">
          玩家列表
        </h3>
        <div class="grid grid-cols-2 gap-2">
          <div
            v-for="player in players"
            :key="player.id"
            class="flex items-center gap-1 p-1.5 md:p-2 bg-gray-50 rounded-lg"
            :class="{ 'bg-blue-50': player.isDrawing }"
          >
            <div class="flex-1 min-w-0">
              <div
                class="text-xs md:text-sm font-medium truncate"
                :class="{ 'text-blue-600': player.isDrawing }"
              >
                {{ player.name }}
              </div>
              <div class="text-[10px] md:text-xs text-gray-500">
                {{ player.score }}分
              </div>
            </div>
            <div
              v-if="player.isDrawing"
              class="text-[10px] md:text-xs text-blue-600 whitespace-nowrap"
            >
              画画中
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
import { useGameStore } from "../stores/game";
import type { Player, ChatMessage } from "../types/game";

const props = defineProps<{
  isDrawer: boolean;
  currentWord?: string;
  timeLeft: number;
  gameStatus: string;
  players: Player[];
  messages: ChatMessage[];
  currentRound?: number;
  maxRounds?: number;
  gameProgress?: number;
  canStartGame?: boolean;
  isMobile?: boolean;
  isCollapsed?: boolean;
}>();

const emit = defineEmits<{
  guess: [guess: string];
  "start-game": [];
  "toggle-collapse": [];
}>();

const gameStore = useGameStore();
const guessInput = ref("");
const chatContainer = ref<HTMLElement>();

// 响应式样式
const isMobile = computed(() => window.innerWidth < 768);

const panelClass = computed(() => ({
  "panel-mobile": isMobile.value,
  "panel-desktop": !isMobile.value,
}));

const gameStatusText = computed(() => {
  switch (props.gameStatus) {
    case "waiting":
      return "等待开始";
    case "drawing":
      return "游戏中";
    case "guessing":
      return "猜词中";
    case "finished":
      return "游戏结束";
    default:
      return "未知状态";
  }
});

const timeProgress = computed(() => {
  const maxTime = 60; // 假设每轮60秒
  return Math.max(0, (props.timeLeft / maxTime) * 100);
});

// 获取消息样式类
const getMessageClass = (type: string) => {
  switch (type) {
    case "guess":
      return "text-blue-600";
    case "correct":
      return "text-green-600 font-bold";
    case "system":
      return "text-gray-500 italic";
    default:
      return "text-gray-600";
  }
};

const submitGuess = () => {
  if (!guessInput.value.trim()) return;

  gameStore.sendGuess(guessInput.value.trim());
  guessInput.value = "";
};

// 自动滚动到最新消息
watch(
  () => props.messages,
  () => {
    nextTick(() => {
      if (chatContainer.value) {
        chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
      }
    });
  },
  { deep: true }
);
</script>

<style scoped>
.guess-panel {
  background: white;
  border-radius: 0.5rem;
  padding: 1rem;
}

.panel-mobile {
  /* 手机端：占据下半部分 */
  height: 50vh;
  margin: 0;
  border-radius: 0;
  border-top: 1px solid #e5e7eb;
}

.panel-desktop {
  /* 电脑端：悬浮卡片 */
  position: fixed;
  top: 20px;
  right: 20px;
  width: 320px;
  max-height: calc(100vh - 40px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  z-index: 20;
}

.guess-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  min-height: 0;
}

.current-word {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.8;
  }
}

/* 聊天滚动条样式 */
.chat-messages div::-webkit-scrollbar {
  width: 4px;
}

.chat-messages div::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.chat-messages div::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.chat-messages div::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
</style>
